from playwright.sync_api import Page
from typing import Dict, Any

from service.ResDataService import get_end_data
from service.StatusEnum import StatusEnum
from tools.Result import success_result, error_result

# 全局存储响应数据（可根据需求调整）
response_data = {}


def handle_response(response):
    """响应处理器（带数据收集功能）"""
    global response_data
    # 记录所有响应URL

    if "getInfoForGateway" in response.url:
        response_data["info"] = response.json()
    if "pageListByTarget" in response.url:
        response_data["list"] = response.json()



def get_html_detail(page: Page, detail_url: str) -> Dict[str, Any]:
    """获取页面详情并捕获响应数据"""
    global response_data
    # 清空历史数据
    response_data = {}
    # 设置响应监听器
    page.on("response", handle_response)
    try:
        page.goto( detail_url,  wait_until="networkidle",  timeout=15000 )
        # 等待关键元素出现（根据实际页面调整）
        page.wait_for_timeout(800)
        # 返回收集到的响应数据
        return success_result("获取成功", get_result(response_data))

    except Exception as e:
        return error_result(f"页面加载失败: {str(e)}")

def get_result(data):
    # 安全获取list数据
    list_data = data.get("list", {}).get("data", {}).get("records",[]) if isinstance(data.get("list"), dict) else []
    current_price = list_data[0]["bidPrice"] if list_data else ""

    # 安全获取info数据
    info_data = data.get("info", {}).get("data", {}) if isinstance(data.get("info"), dict) else {}
    start_price = info_data.get("startingUnitPrice", "")
    status = info_data.get("targetsStatusId","")

    return get_end_data( start_price, current_price,StatusEnum.get_ztep_statust_info(show_status=status))
